/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.form.process.service;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.GspProject;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import com.inspur.edp.lcm.metadata.api.service.NoCodeService;
import com.inspur.edp.metadata.businesstype.api.MdBizTypeMappingService;
import com.inspur.edp.web.form.process.api.service.FormProcessService;
import com.inspur.edp.wf.bizprocess.entity.FormFormat;
import com.inspur.edp.wf.bizprocess.entity.UrlParameter;
import com.inspur.edp.wf.bizprocess.service.FormFormatRpcService;
import io.iec.edp.caf.businessobject.api.entity.DevBasicBoInfo;
import io.iec.edp.caf.businessobject.api.service.DevBasicInfoService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.client.RpcClassHolder;

import java.util.Arrays;
import java.util.List;

public class FormProcessServiceImpl implements FormProcessService {

    private static class LazyHolder {
        private static final FormProcessServiceImpl INSTANCE = new FormProcessServiceImpl();
    }
    public FormProcessServiceImpl() {}

    public static final FormProcessServiceImpl getInstance() {
        return LazyHolder.INSTANCE;
    }

    public void publishFormFormat(String formId, String formPath) {
        if (formPath == null || formPath.equals("")) {
            throw new RuntimeException("参数path不允许为空。");
        }

        String unifiedPath = formPath.replace('\\', '/');
        if (unifiedPath.startsWith("/")) {
            unifiedPath = unifiedPath.substring(1); // 去掉开头的/
        }

        MetadataService metadataService = SpringBeanUtils.getBean(MetadataService.class);

        List<GspMetadata> mdList = metadataService.getMetadataList(unifiedPath);
        GspMetadata md = mdList.stream().filter(item -> item.getHeader().getId().equals(formId)).findFirst().orElse(null);
        if (md == null) {
            throw new RuntimeException("找不到表单元数据: " + formId + "。文件路径:" + unifiedPath + "。");
        }
        MetadataHeader header = md.getHeader();
        GspProject project = metadataService.getGspProjectInfo(unifiedPath);
        String deploymentPath = project.getSuDeploymentPath();
        String projectName = project.getMetadataProjectName().toLowerCase();
        String url = "/" + deploymentPath + "/web/" + projectName + "/" + "index.html#/" + header.getCode();
        String boId = project.getBizobjectID();

        pushFormFormat(formId, md, url, boId);
    }

    @Override
    public void publishFormFormatForNoCode(String formId, String boId, String microAppCode, String deviceType) {


        // 获取表单
        NoCodeService noCodeService =SpringBeanUtils.getBean(NoCodeService.class);
        GspMetadata formMetadata = noCodeService.getMetadata(formId);

        // 根据bo获取app/su路径
        DevBasicInfoService devBasicInfoService = SpringBeanUtils.getBean(DevBasicInfoService.class);
        DevBasicBoInfo boInfo = devBasicInfoService.getDevBasicBoInfo(boId);
        String deploymentPath = boInfo.getAppCode() + "/" + boInfo.getSuCode();

        // \web\apps\scm\sd\web\bo-salesorder2103front
        String devicePath = "mobile".equals(deviceType) ? "mob" : "web";
        String url = "/" + deploymentPath + "/" + devicePath + "/" + microAppCode + "/" + "index.html#/" + formMetadata.getHeader().getCode();

        pushFormFormat(formId, formMetadata, url, boId);
    }

    private void pushFormFormat(String formId, GspMetadata formMetadta, String url, String boId) {
        // 组织参数，调用工作流接口。
        FormFormat ff = new FormFormat();
        ff.setId(formId);
        ff.setCode(formMetadta.getHeader().getCode());
        ff.setName(formMetadta.getHeader().getName());
        ff.setUrlType("url");
        ff.setFormUrl(url);

        UrlParameter actionParam = new UrlParameter();
        actionParam.setCode("action");
        actionParam.setName("动作");
        actionParam.setValue("LoadAndView1");
        UrlParameter idParam = new UrlParameter();
        idParam.setCode("id");
        idParam.setName("内码");
        idParam.setValue("{\"expr\":\"DefaultFunction.GetContextParameter(\\\"dataId\\\")\",\"sexpr\":\"\"}\n");
        List list = Arrays.asList(actionParam, idParam);
        // UrlParameter param1 = new UrlParameter();
        // param1.setCode("expr");
        // param1.setValue("DefaultFunction.GetContextParameter(\\\"dataId\\\")");
        // UrlParameter param2 = new UrlParameter();
        // param2.setCode("sexpr");
        // param2.setValue("");
        // List list = Arrays.asList(param1, param2);
        ff.setUrlParameters(list);
        ff.setFormatType("wf");

        ff.setBizCategory(getBizTypeId(boId));

        RpcClassHolder rpcHelper = SpringBeanUtils.getBean(RpcClassHolder.class);
        FormFormatRpcService service = rpcHelper.getRpcClass(FormFormatRpcService.class);
        service.addFormFormat(ff);
    }

    private String getBizTypeId(String bizObjectId) {
        MdBizTypeMappingService service = SpringBeanUtils.getBean(MdBizTypeMappingService.class);
        List<String> bizTypeIds = service.getBizTypeIdsByBoId(bizObjectId);
        return bizTypeIds == null || bizTypeIds.size() == 0 ? "" : bizTypeIds.get(0);
    }
}
